package cn.uin.domain.auth.service.user.login;

import cn.uin.domain.auth.adapter.repository.IAuthRepository;
import cn.uin.domain.auth.model.entity.HomeMenuEntity;
import cn.uin.domain.auth.model.entity.HomeRoleEntity;
import cn.uin.domain.auth.model.entity.HomeUserEntity;
import cn.uin.domain.auth.model.entity.UserInfoDetailEntity;
import cn.uin.types.enums.ResponseCode;
import cn.uin.types.exception.AppException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Auther: uIn
 * @Date: 2025/10/19 - 10 - 19 - 17:05
 * @Description: 自定义UserDetailService
 * @version: 1.0
 */
@Component
public class CustomUserDetailService implements UserDetailsService {

    @Resource
    private IAuthRepository iAuthRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfoDetailEntity userInfoDetailEntity = new UserInfoDetailEntity();
        HomeUserEntity homeUser = iAuthRepository.queryUserByUserName(username);
        if (ObjectUtils.isEmpty(homeUser)) {
            throw new AppException(ResponseCode.A0009.getCode(), ResponseCode.A0009.getInfo());
        }
        userInfoDetailEntity.setUsername(homeUser.getUsername());
        userInfoDetailEntity.setPassword(homeUser.getPassword());
        userInfoDetailEntity.setPhone(homeUser.getPhone());
        userInfoDetailEntity.setEmail(homeUser.getEmail());
        userInfoDetailEntity.setStatus(homeUser.getStatus());

        // 根据用户名获取权限菜单
        List<HomeMenuEntity> homeMenuList = iAuthRepository.queryMenusByUserName(username);
        userInfoDetailEntity.setMenus(homeMenuList);
        return userInfoDetailEntity;
    }
}
